/*
const express = require('express');
const app = express();
const routerInit = require("./router/index")
const path = require('path')
app.use('/', express.static(path.join(__dirname, '../static')))
// express.json()函数是Express中的内置中间件函数
// 它使用body-parser解析带有JSON有效负载的传入请求 解析后req.body.参数名  就可以直接使用
// 参考https://vimsky.com/examples/usage/express-js-express-json-function.html
app.use(express.json())
routerInit(app);

app.get('/', function (req, res) {
   res.send('Hello World');
})
 
const server = app.listen(8081, function () {
    const host = server.address().address
    const port = server.address().port
 
  console.log("应用实例，访问地址为 http://%s:%s", host, port)
 
})
*/
var net = require('net');
var protobuf = require('protocol-buffers');
const fs = require('fs');
var qms = protobuf(fs.readFileSync('./static/resources/QueryProto.proto'));
var rms = protobuf(fs.readFileSync('./static/resources/ResultProto.proto'));
//模块引入
var listenPort = 8080;//监听端口
var server = net.createServer(function(socket){
  let query;

 // 创建socket服务端
 console.log('connect: ',socket.remoteAddress + ':' + socket.remotePort);
 //接收到数据
 var buffer=Buffer.from("");
 socket.on('data',function(data){
  console.log("调用data数据为：",data,data.toString());
  buffer = Buffer.concat([buffer,data]);//因为data使用了多次
 });

 socket.on('end', function() {
  console.log("总共传输的buffer为:",buffer);
  query = qms.QueryProto.decode(buffer);
  console.log("end，最后结果为：",query)
  let sum = query.first+query.second;
  let buf = rms.ResultProto.encode({
    sum: sum
  })
  socket.write(buf);
});

 //数据错误事件
 socket.on('error',function(exception){
  console.log('socket error:' + exception);
  socket.end();
 });
 //客户端关闭事件
 socket.on('close',function(data){
  console.log('client closed!');
   // socket.remoteAddress + ' ' + socket.remotePort);
 });
}).listen(listenPort);
//服务器监听事件
server.on('listening',function(){
 console.log("server listening:" + server.address().port);
});
//服务器错误事件
server.on("error",function(exception){
 console.log("server error:" + exception);
});